package cn.edu.swu.miniwebsvr.core;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private final Config config = Config.getInstance();
    private final ExecutorService threadPool = Executors.newFixedThreadPool(10);
    private volatile boolean isRunning = true;

    public void start() {
        // TODO: [222024321072047/李明燊] 实现 ServerSocket 的创建和监听
        try (ServerSocket serverSocket = new ServerSocket(config.getPort())) {
            System.out.println("MiniWebSvr 启动成功，监听端口：" + config.getPort());
            System.out.println("Web根目录：" + config.getWebRoot());
            System.out.println("服务器运行中，按 Ctrl+C 停止服务");

            while (isRunning) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    System.out.println("接收到新的连接：" + clientSocket.getInetAddress() + ":" + clientSocket.getPort());
                    threadPool.execute(new RequestProcessor(clientSocket));
                } catch (IOException e) {
                    if (isRunning) {
                        System.err.println("接受客户端连接时发生异常: " + e.getMessage());
                    } else {
                        System.out.println("服务器正在关闭...");
                        break;
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("服务器启动失败，端口 " + config.getPort() + " 可能已被占用: " + e.getMessage());
        } finally {
            stop();
        }
    }

    public void stop() {
        isRunning = false;
        threadPool.shutdown();
        System.out.println("服务器已停止");
    }

    private static class RequestProcessor implements Runnable {
        private final Socket socket;

        public RequestProcessor(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            // TODO: [222024321072047/李明燊] 完善请求处理流程，确保异常安全和资源关闭
            try {
                // 设置socket超时时间，避免客户端长时间不发送数据
                socket.setSoTimeout(30000); // 30秒超时

                // 解析HTTP请求
                Parameter request = HttpParser.parse(socket.getInputStream());

                if (request != null) {
                    System.out.println("处理请求: " + request.getMethod() + " " + request.getUrl());

                    // 路由请求到对应的处理器
                    Router router = new Router();
                    router.route(request, socket.getOutputStream());

                    System.out.println("请求处理完成: " + request.getMethod() + " " + request.getUrl());
                } else {
                    System.err.println("无法解析HTTP请求");
                    sendErrorResponse(400, "Bad Request");
                }

            } catch (Exception e) {
                System.err.println("请求处理异常: " + e.getMessage());
                e.printStackTrace();

                // TODO: [222024321072047/李明燊] 可以在这里实现返回 500 错误页面的逻辑
                try {
                    sendErrorResponse(500, "Internal Server Error");
                } catch (IOException ioException) {
                    System.err.println("发送错误响应失败: " + ioException.getMessage());
                }
            } finally {
                // 确保资源被正确关闭
                closeSocket();
            }
        }

        private void sendErrorResponse(int statusCode, String statusMessage) throws IOException {
            String response = "HTTP/1.1 " + statusCode + " " + statusMessage + "\r\n" +
                    "Content-Type: text/html; charset=utf-8\r\n" +
                    "Connection: close\r\n" +
                    "\r\n" +
                    "<html><body><h1>" + statusCode + " " + statusMessage + "</h1></body></html>";
            socket.getOutputStream().write(response.getBytes("UTF-8"));
            socket.getOutputStream().flush();
        }

        private void closeSocket() {
            if (socket != null && !socket.isClosed()) {
                try {
                    socket.close();
                    System.out.println("连接已关闭: " + socket.getInetAddress() + ":" + socket.getPort());
                } catch (IOException e) {
                    System.err.println("关闭socket时发生异常: " + e.getMessage());
                }
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server();

        // 添加关闭钩子，确保服务器优雅关闭
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("\n接收到关闭信号，正在停止服务器...");
            server.stop();
        }));

        server.start();
    }
}
